<template>
    <div class="login-view">
        <div class="login-container">
            <!-- 左侧装饰 -->
            <div class="login-banner">
                <div class="banner-content">
                    <h1 class="banner-title">
                        <el-icon>
                            <Reading />
                        </el-icon>
                        水土TU
                    </h1>
                    <p class="banner-subtitle">欢迎回来</p>
                    <p class="banner-desc">分享生活，记录成长，探索更多精彩内容</p>
                </div>
            </div>

            <!-- 右侧登录表单 -->
            <div class="login-form-wrapper">
                <el-card class="login-card" shadow="never">
                    <div class="form-header">
                        <h2>用户登录</h2>
                        <p>登录以解锁更多精彩内容</p>
                    </div>

                    <el-form :model="userForm" :rules="rules" ref="formRef" @submit.prevent="loginFn" size="large">
                        <el-form-item prop="account">
                            <el-input v-model="userForm.account" placeholder="请输入账号" :prefix-icon="User" clearable />
                        </el-form-item>

                        <el-form-item prop="password">
                            <el-input v-model="userForm.password" type="password" placeholder="请输入密码"
                                :prefix-icon="Lock" show-password clearable />
                        </el-form-item>

                        <el-form-item>
                            <el-button type="primary" native-type="submit" :loading="loading" style="width: 100%"
                                size="large">
                                {{ loading ? '登录中...' : '登录' }}
                            </el-button>
                        </el-form-item>
                    </el-form>

                    <div class="form-footer">
                        <el-divider>
                            <span class="divider-text">其他操作</span>
                        </el-divider>
                        <div class="footer-links">
                            <router-link to="/register" class="link">
                                <el-icon>
                                    <UserFilled />
                                </el-icon>
                                没有账号，立即注册
                            </router-link>
                            <router-link to="/home" class="link">
                                <el-icon>
                                    <HomeFilled />
                                </el-icon>
                                返回首页
                            </router-link>
                        </div>
                    </div>
                </el-card>
            </div>
        </div>
    </div>
</template>

<script setup lang="ts">
import { login } from '@/api'
import { reactive, ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import type { FormInstance, FormRules } from 'element-plus'
import { User, Lock, UserFilled, HomeFilled, Reading } from '@element-plus/icons-vue'

const router = useRouter()
const formRef = ref<FormInstance>()
const loading = ref(false)

interface IUser {
    account: string
    password: string
}

const userForm = reactive<IUser>({
    account: "",
    password: ""
})

const rules: FormRules = {
    account: [
        { required: true, message: '请输入账号', trigger: 'blur' },
        { min: 3, max: 20, message: '账号长度在 3 到 20 个字符', trigger: 'blur' }
    ],
    password: [
        { required: true, message: '请输入密码', trigger: 'blur' },
        { min: 6, max: 20, message: '密码长度在 6 到 20 个字符', trigger: 'blur' }
    ]
}

const loginFn = async () => {
    if (!formRef.value) return

    await formRef.value.validate(async (valid) => {
        if (!valid) return

        loading.value = true
        try {
            const { account, password } = userForm
            const resData: any = await login({ account, password })

            if (resData.code == 200) {
                const { token, role, username, account, imgUrl } = resData
                localStorage.setItem("AUTO_TOKEN", token)
                if (role) {
                    localStorage.setItem("USER_ROLE", role)
                }
                // 保存用户名，如果没有返回用户名则使用账号
                if (username) {
                    localStorage.setItem("USERNAME", username)
                } else if (account) {
                    localStorage.setItem("USERNAME", account)
                }
                // 保存头像URL（如果返回了）
                if (imgUrl) {
                    localStorage.setItem("USER_AVATAR", imgUrl)
                }
                // 触发自定义事件通知 LayoutView 更新
                window.dispatchEvent(new Event('storage'))
                ElMessage.success(resData.msg || '登录成功')

                setTimeout(() => {
                    ElMessageBox.confirm(
                        '登录成功！是否跳转到个人中心？',
                        '提示',
                        {
                            confirmButtonText: '个人中心',
                            cancelButtonText: '返回首页',
                            type: 'success',
                        }
                    ).then(() => {
                        router.push({ path: '/user' })
                    }).catch(() => {
                        router.push({ path: '/home' })
                    })
                }, 300)
            } else if (resData.code == -2) {
                // 账号被封禁
                ElMessageBox.alert(
                    resData.msg || '该账号已被封禁，请更换账号登录或联系管理员解封',
                    '账号被封禁',
                    {
                        confirmButtonText: '确定',
                        type: 'error',
                    }
                )
            } else {
                ElMessage.error(resData.msg || '登录失败')
            }
        } catch (error) {
            ElMessage.error('登录失败，请稍后重试')
        } finally {
            loading.value = false
        }
    })
}
</script>

<style lang="less" scoped>
@import "../assets/varable.less";

.login-view {
    min-height: 100vh;
    background: linear-gradient(135deg, @primary-lighter 0%, @bg-white 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px 20px;
}

.login-container {
    display: flex;
    width: 100%;
    max-width: 1000px;
    min-height: 600px;
    background: @bg-white;
    border-radius: 20px;
    box-shadow: @shadow-lg;
    overflow: hidden;
}

.login-banner {
    flex: 1;
    background: linear-gradient(135deg, @primary-color 0%, @primary-dark 100%);
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 60px;
    color: @text-white;
    position: relative;
    overflow: hidden;

    &::before {
        content: '';
        position: absolute;
        width: 200%;
        height: 200%;
        background: radial-gradient(circle, rgba(255, 255, 255, 0.1) 1px, transparent 1px);
        background-size: 40px 40px;
        animation: float 20s linear infinite;
    }

    .banner-content {
        position: relative;
        z-index: 1;
        text-align: center;

        .banner-title {
            font-size: 48px;
            font-weight: bold;
            margin-bottom: 20px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 15px;

            .el-icon {
                font-size: 56px;
            }
        }

        .banner-subtitle {
            font-size: 28px;
            margin-bottom: 15px;
            opacity: 0.95;
        }

        .banner-desc {
            font-size: 16px;
            opacity: 0.85;
            line-height: 1.8;
        }
    }
}

@keyframes float {
    0% {
        transform: translate(0, 0);
    }

    100% {
        transform: translate(-40px, -40px);
    }
}

.login-form-wrapper {
    flex: 1;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 40px;
}

.login-card {
    width: 100%;
    max-width: 420px;
    border: none;

    :deep(.el-card__body) {
        padding: 40px;
    }

    .form-header {
        text-align: center;
        margin-bottom: 40px;

        h2 {
            font-size: 28px;
            font-weight: bold;
            color: @text-primary;
            margin-bottom: 10px;
        }

        p {
            color: @text-secondary;
            font-size: 14px;
        }
    }

    .el-form {
        .el-form-item {
            margin-bottom: 24px;

            &:last-of-type {
                margin-bottom: 0;
            }
        }
    }

    .form-footer {
        margin-top: 30px;

        .divider-text {
            color: @text-light;
            font-size: 13px;
        }

        .footer-links {
            display: flex;
            justify-content: space-between;
            flex-wrap: wrap;
            gap: 15px;
            margin-top: 20px;

            .link {
                display: flex;
                align-items: center;
                gap: 6px;
                color: @primary-color;
                text-decoration: none;
                font-size: 14px;
                transition: all 0.3s;

                &:hover {
                    color: @primary-dark;
                    transform: translateX(3px);
                }

                .el-icon {
                    font-size: 16px;
                }
            }
        }
    }
}

// 响应式设计
@media (max-width: 992px) {
    .login-banner {
        display: none;
    }

    .login-form-wrapper {
        flex: none;
        width: 100%;
    }
}

@media (max-width: 768px) {
    .login-view {
        padding: 20px;
    }

    .login-container {
        min-height: auto;
        border-radius: 16px;
    }

    .login-form-wrapper {
        padding: 20px;
    }

    .login-card {
        :deep(.el-card__body) {
            padding: 30px 20px;
        }

        .form-header {
            margin-bottom: 30px;

            h2 {
                font-size: 24px;
            }
        }
    }
}

@media (max-width: 576px) {
    .login-view {
        padding: 15px;
    }

    .login-container {
        border-radius: 12px;
    }

    .login-card {
        :deep(.el-card__body) {
            padding: 25px 15px;
        }

        .form-footer {
            .footer-links {
                flex-direction: column;
                align-items: center;
            }
        }
    }
}
</style>
